package juc.demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadTest2 {

    public static void main(String[] args) {
        Alternate alternate = new Alternate();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 50; i++) {
                    alternate.subLoop(i);
                }
            }
        }, "子线程").start();

        for (int i = 1; i <= 50; i++) {
            alternate.mainLoop(i);
        }
    }

}

class Alternate {

    /**
     * 执行标记
     */
    private int number = 1;

    private Lock lock = new ReentrantLock();

    private Condition subCondition = lock.newCondition();
    private Condition mainCondition = lock.newCondition();

    public void subLoop(int totalLoop) {

        lock.lock();

        try {

            // 判断
            if (number != 1) {
                subCondition.await();
            }

            for (int i = 1; i <= 10; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + "循环" + i + "次" + "\t"
                        + "第" + totalLoop + "轮");
            }

            number = 2;
            mainCondition.signal();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void mainLoop(int totalLoop) {
        lock.lock();

        try {

            // 判断
            if (number != 2) {
                mainCondition.await();
            }

            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + "循环" + i + "次" + "\t"
                        + "第" + totalLoop + "轮");
            }

            number = 1;
            subCondition.signal();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
